package com.uwo.commons.kits;


import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;

/**
 * json格式转换
 * @author hao.yan
 */
public class JsonKits {

    private static final Logger log = LoggerFactory.getLogger(JsonKits.class);

    /**
     * json转Object
     * @param json
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> T json2Object(String json, Class<T> clazz){
        try {
            ObjectMapper mapper = new ObjectMapper();
            mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
            return mapper.readValue(json, clazz);
        } catch (IOException e) {
            log.error("{}", e);
            return null;
        }
    }

    /**
     * object转json
     * @param entity
     * @return
     */
    public static <T> String object2Json(T entity){
        try {
            ObjectMapper mapper = new ObjectMapper();
            return mapper.writeValueAsString(entity);
        } catch (JsonProcessingException e) {
            log.error("{}", e);
            return null;
        }
    }

}
